package com.itic.mall.mobile.jd;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcabi.http.Request;
import com.jcabi.http.request.ApacheRequest;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.request.cps.ServicePromotionCouponGetCodeBySubUnionIdRequest;
import com.jd.open.api.sdk.request.cps.ServicePromotionWxsqGetCodeBySubUnionIdRequest;
import com.jd.open.api.sdk.response.cps.ServicePromotionCouponGetCodeBySubUnionIdResponse;
import com.jd.open.api.sdk.response.cps.ServicePromotionWxsqGetCodeBySubUnionIdResponse;


public class MallJdUtils {
	
	private static String baseUrl = "http://yhjcms.jhjvip.cn";
	private static String unionId = "1000169071";
	
	private static String access_token  = MallJdConfig.getAccesstoken();
	private static String app_key  = MallJdConfig.getKey();
	private static String app_secret  = MallJdConfig.getSecret();
	private static String jd_api_url = MallJdConfig.getUrl();
	
	public static JSONArray queryProductList(int pageIndex, int pageSize) {
		JSONObject req = new JSONObject();
		req.put("page", pageIndex + 1);
		req.put("pageSize", pageSize);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdProductService/queryProductList.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp).getJSONObject("result").getJSONArray("description");
		} catch (Exception e) {
			return null;
		}
	}

	
	public static String convert(String userId, String sku, String couponUrl) {
		userToChannel(userId);
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("subUnionId", unionId);
		Map<String, String> pcmap = new HashMap<>();
		pcmap.put(sku, couponUrl);
		req.put("pcmap", pcmap);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/couponGetCodeBySubUnionId.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //  
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			
			
			return JSON.parseObject(resp).getJSONObject("result").getJSONObject("urlList")
					.getString(couponUrl + "," + sku);
		} catch (Exception e) {
			return null;
		}
	}


	public static Map<String, String> convert(String userId, Map<String, String> skuMaptoCouponUrl) {
		Map<String, String> result = new HashMap<>();
		userToChannel(userId);
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("subUnionId", unionId);
		req.put("pcmap", skuMaptoCouponUrl);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/couponGetCodeBySubUnionId.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			JSONObject urls = JSON.parseObject(resp).getJSONObject("result").getJSONObject("urlList");
			for (String key : urls.keySet()) {
				result.put(key.substring(key.lastIndexOf(",") + 1), urls.getString(key));
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	


	public static JSONObject queryCommissionByUserId(String userId, long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/getCommissionByUserid.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	public  static JSONObject queryOrderList(long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/OrderDetail.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	
	public static JSONObject orderSettlementDetail(long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/orderSettlementDetail.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	public static JSONObject userToChannel(String userId) {
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/userToChannel.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}
	
	
	public static String subConvert( String skuId,String positionId ){
		JdClient client=new DefaultJdClient(jd_api_url,access_token,app_key,app_secret);
		String codeBySubUnionId	 = null; //返回链接
		ServicePromotionWxsqGetCodeBySubUnionIdRequest requestJd = null;//普通转链请求
		ServicePromotionWxsqGetCodeBySubUnionIdResponse responseJd = null; //普通转链返回
		try {
			requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
			requestJd.setProCont( 1 ); //推广内容：1单品
			requestJd.setMaterialIds(skuId); //推广物料：单品skuId
			requestJd.setPositionId(Integer.parseInt(positionId));
			responseJd=client.execute(requestJd);
			//解析返回参数
			if( "0".equals(responseJd.getCode()) ){
				String result2 = responseJd.getGetcodebysubunionidResult();
				if( result2.contains("urlList") ){
					JSONObject urls = JSON.parseObject(result2).getJSONObject("urlList");
					for (String key : urls.keySet()) {
						key = (String) urls.get(key);
						codeBySubUnionId = key;
					}
				}
			}
		} catch (JdException e) {
			e.printStackTrace();
		}
   		return codeBySubUnionId;
	}
	
	/**
	 * 京东优惠券二合一转链接
	 * @author 王文鑫
	 * @date 2017年12月28日 下午2:53:41
	 * @param couponUrl  优惠券领取链接 
	 * @param materialIds 推广物料：单品skuId 
	 * @param subUnionId 子联盟ID 
	 * @param positionId 推广位ID
	 * @return
	 */
	public static String convertNew( String couponUrl ,String materialIds ,String positionId  ){
		
		JdClient client=new DefaultJdClient(jd_api_url,access_token,app_key,app_secret);
		String codeBySubUnionId	 = null; //返回链接
		ServicePromotionCouponGetCodeBySubUnionIdRequest requestHb = null; //红包转链请求
		ServicePromotionWxsqGetCodeBySubUnionIdRequest requestJd = null;//普通转链请求
		
		ServicePromotionWxsqGetCodeBySubUnionIdResponse responseJd = null; //普通转链返回
		ServicePromotionCouponGetCodeBySubUnionIdResponse responseHb = null;
		try {
			//如果红包卷链接为空，则进入普通转链
			if(null == couponUrl){
				requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
		   		requestJd.setProCont( 1 ); //推广内容：1单品
		   		requestJd.setMaterialIds(materialIds); //推广物料：单品skuId
		   		
		   		responseJd=client.execute(requestJd);
		   		//解析返回参数
		   		if( "0".equals(responseJd.getCode()) ){
		   			String result2 = responseJd.getGetcodebysubunionidResult();
		   			if( result2.contains("urlList") ){
		   				JSONObject urls = JSON.parseObject(result2).getJSONObject("urlList");
		   				for (String key : urls.keySet()) {
							key = (String) urls.get(key);
							codeBySubUnionId = key;
						}
		   			}
		   		}
			}else{
				requestHb = new ServicePromotionCouponGetCodeBySubUnionIdRequest();
				//设置三个参数
				requestHb.setCouponUrl( couponUrl );
				requestHb.setMaterialIds( materialIds );
				requestHb.setSubUnionId( unionId );
				/*request.setPositionId( 123 );*/
				
				responseHb = client.execute(requestHb); //红包返回参数
				//解析返回成功参数{"resultCode":"0","resultMessage":"获取代码成功","urlList":{"http://t.cn/ROxE047,15232989992":""}}
				if( "0".equals(responseHb.getCode()) ){
					String result2 = responseHb.getGetcodebysubunionidResult();
					JSONObject urls = JSON.parseObject(result2).getJSONObject("urlList");
					for (String key : urls.keySet()) {
						key = key.substring(0,key.lastIndexOf(","));
						codeBySubUnionId = key;
					}
				}else{ //如果获取红包链接为空 ，则调用普通链接
					requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
			   		requestJd.setProCont( 1 ); //推广内容：1单品
			   		requestJd.setMaterialIds(materialIds); //推广物料：单品skuId
			   		responseJd=client.execute(requestJd);
			   		//解析返回参数
			   		if( "0".equals(responseJd.getCode()) ){
			   			String result2 = responseJd.getGetcodebysubunionidResult();
			   			if( result2.contains("urlList") ){
			   				JSONObject urls = JSON.parseObject(result2).getJSONObject("urlList");
			   				for (String key : urls.keySet()) {
								key = (String) urls.get(key);
								codeBySubUnionId = key;
							}
			   			}
			   		}
				}
			}
			return codeBySubUnionId;
			
		} catch (JdException e1) {
			return null;
		}
	}
}